import re

from enetity_extraction.json_result import generate_return_json


def find_special_substrings(text):
    pattern = r"(人民币.*?\d+.{1,3}元)"
    matches = re.findall(pattern, text)
    return matches


def is_valid_money(text):
    # 示例用法

    special_substrings = find_special_substrings(text)
    # print("满足条件的子串：", special_substrings)
    if special_substrings != []:
        print("金额前不应该加人民币")


def is_valid_thousands_format(amount_str):
    # 定义正则表达式模式
    pattern = r'^\d{1,3}(,\d{3})*(\.\d{2})?$'
    # 使用正则表达式匹配
    match = re.match(pattern, amount_str[0:-1])
    return bool(match)


def extract_trailing_non_digits(s):
    result = ''
    for char in reversed(s):
        if not char.isdigit():
            result = char + result
        else:
            break
    return result


def check_money(data_dic):
    result = generate_return_json()

    if data_dic['金额'] == [] or data_dic['金额'] == {}:
        # print('金额书写错误或无金额')
        result['type'] = '无金额'
        # return result
        return None

    data_list = data_dic['金额']

    substring = '人民币'
    money_substring1 = extract_trailing_non_digits(data_list[0]['match'])
    for item in data_list:
        if substring in item['match']:
            # result赋值
            result['paragraph_index'] = item['paragraph_index']
            result['start'] = item['start_pos']
            result['end'] = item['end_pos']
            # print('金额前面不应该加人民币')
            result['type'] = '金额前面不应该加人民币'
            result['offset'] = item['end_pos'] - item['start_pos'] + 1
            return result
        if not is_valid_thousands_format(item['match']):  # 检查是否是一个合法的三位计数法
            # result赋值
            result['paragraph_index'] = item['paragraph_index']
            result['start'] = item['start_pos']
            result['end'] = item['end_pos']
            # print('金额前面不应该加人民币')
            result['type'] = '建议采用三位计数法'
            result['offset'] = item['end_pos'] - item['start_pos'] + 1
            return result
        if not extract_trailing_non_digits(item['match']):
            result['paragraph_index'] = item['paragraph_index']
            result['start'] = item['start_pos']
            result['end'] = item['end_pos']
            # print('金额前面不应该加人民币')
            result['type'] = '金额不规范'
            result['offset'] = item['end_pos'] - item['start_pos'] + 1
            return result
        elif extract_trailing_non_digits(item['match']) != money_substring1:
            result['paragraph_index'] = item['paragraph_index']
            result['start'] = item['start_pos']
            result['end'] = item['end_pos']
            # print('金额前面不应该加人民币')
            result['type'] = '金额单位不一致'
            result['offset'] = item['end_pos'] - item['start_pos'] + 1
            return result

    result['type'] = '金额合法'
    # return result
    # return None


if __name__ == "__main__":
    test_text = "这是一段测试文本，其中包含人民币100元、200元和人民币1000000元。但是1000元在这里不应该被匹配。"
    is_valid_money(test_text)
